﻿using System;
using System.Collections.Generic;
using System.Linq;
using Model;
using DBUtility;
using MySql.Data.MySqlClient;

namespace DAL
{
    public class UserRepository
    {
        /// 添加用户
        public int AddUser(User user)
        {
            string sql = @"INSERT INTO user 
                            (Username, Password, LastLoginTime) 
                           VALUES 
                            (@Username, @Password, @LastLoginTime)";

            MySqlParameter[] parameters = {
                new MySqlParameter("@Username", user.Username),
                new MySqlParameter("@Password", user.Password),
                new MySqlParameter("@LastLoginTime", user.LastLoginTime)
            };

            return DBHelper.ExecuteNonQuery(sql, parameters);
        }

        /// 删除用户
        public int DeleteUser(int userId)
        {
            string sql = "DELETE FROM user WHERE UserId = @UserId";
            MySqlParameter[] parameters = { new MySqlParameter("@UserId", userId) };
            return DBHelper.ExecuteNonQuery(sql, parameters);
        }

        /// 更新用户信息
        public int UpdateUser(User user)
        {
            string sql = @"UPDATE user 
                            SET Username = @Username, 
                                Password = @Password, 
                                LastLoginTime = @LastLoginTime 
                          WHERE UserId = @UserId";

            MySqlParameter[] parameters = {
                new MySqlParameter("@Username", user.Username),
                new MySqlParameter("@Password", user.Password),
                new MySqlParameter("@LastLoginTime", user.LastLoginTime),
                new MySqlParameter("@UserId", user.UserId)
            };

            return DBHelper.ExecuteNonQuery(sql, parameters);
        }

        /// 查询所有用户
        public List<User> GetAllUsers()
        {
            string sql = "SELECT * FROM user";
            return DBHelper.ExecuteQuery(sql, null, MapUser);
        }

        /// 根据ID查询单个用户
        public User GetUserById(int userId)
        {
            string sql = "SELECT * FROM user WHERE UserId = @UserId";
            MySqlParameter[] parameters = { new MySqlParameter("@UserId", userId) };
            var users = DBHelper.ExecuteQuery(sql, parameters, MapUser);
            return users.FirstOrDefault();
        }

        /// 映射数据库查询结果到 User 对象
        private User MapUser(MySqlDataReader reader)
        {
            return new User
            {
                UserId = (int)reader["UserId"],
                Username = reader["Username"].ToString(),
                Password = reader["Password"].ToString(),
                LastLoginTime = (DateTime)reader["LastLoginTime"]
            };
        }
    }
}